import dayjs from "dayjs";
// import duration from "dayjs/plugin/duration"
import duration from '@src/common/duration'
import utc from '@src/common/utc'
import weekday from '@src/common/weekday'
dayjs.extend(duration)
dayjs.extend(utc)
dayjs.extend(weekday)

import base from "@src/store/base";
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";

const TITLE_MAP = {
  'SELF_PICKUP': '到店',
  'EXPRESS': '发货',
  'LOCAL': '配送',
}

Component({
  options: {
    addGlobalClass: true,
  },
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: base,
    fields: ['themeColor', 'themeTitleColor']
  }
  ],
  properties: {
    delivery: {
      type: Object
    }
  },
  data: {
    dialogShow: false,
    activeTab: 0,
    headerHeight: 0,
    curIndex: 0,
    curIndex2: null,
    title: '',
    defaultPrepareTips: '',
    tabList: [],
    dateList: [],
    defaultTime: '',
  },
  observers: {
    'delivery': function (delivery) {
      if (delivery && delivery.status === 1) {
        this.init(delivery);
      }
    }
  },
  methods: {
    init(delivery) {
      this.initDisplayInfo(delivery)
      this.initSelectTime(delivery)
    },
    initSelectTime(delivery) {
      let { prepareTime, serviceTimes, bookingSpan, selectSpan, prepareBeginTime } = delivery;
      // console.log('dayjs()', dayjs(prepareBeginTime));
      let recentTime = dayjs();
      if (!prepareBeginTime) { recentTime = recentTime.add(prepareTime + 1, 'minutes') } else {
        let now = dayjs()
        recentTime = dayjs(prepareBeginTime);
        if (recentTime.isBefore(now)) {
          recentTime = now;
        }
      }
      let weekdayMap = this.parseServiceTimes(serviceTimes, selectSpan)
      // console.log("recentTime", recentTime)
      let weekOptions = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
      let dateList = []
      let bookingDays = bookingSpan.value;

      for (let i = 0; i < bookingDays + 1; i++) {
        let date = recentTime.add(i, 'days').format("YYYY-MM-DD");
        let curDay = dayjs(date);
        let month = curDay.format("MM-DD");
        let week = curDay.weekday();
        let timeSpanList = weekdayMap[String(week)];
        if (!timeSpanList) { return }
        if (timeSpanList.length <= 0) {
          continue;
        }

        let dateItem = { date: date, month: month, week: weekOptions[week] }
        if (curDay.isAfter(recentTime)) {
          // 无需过滤
          dateItem['timeList'] = timeSpanList;
          dateList.push(dateItem)
          continue
        }
        // 过滤备货时间
        let list = [];
        timeSpanList.forEach(item => {
          if (curDay.add(item, "minutes").isAfter(recentTime)) {
            list.push(item);
          }
        })
        if (list.length > 0) {
          dateItem['timeList'] = list;
          dateList.push(dateItem)
        }
      }
      this.setData({ dateList })
    },
    parseServiceTimes(serviceTimes, selectSpan) {
      // 可选时段
      let span = 30;
      if (selectSpan.type === 'MINUTES') {
        span = selectSpan.value
      } else if (selectSpan.type === 'HOURS') {
        span = selectSpan.value * 60;
      }
      if (span <= 0 || span >= 1440) {
        span = 30
      }
      let timeSpanList = [];
      let cur = 0;
      while (cur < 1440) {
        timeSpanList.push(cur);
        cur = cur + span;
      }
      // 没有服务时间
      if (!serviceTimes || serviceTimes.length === 0) {
        let weekdayMap = {}
        for (let i = 0; i <= 6; i++) {
          weekdayMap[String(i)] = timeSpanList;
        }
        return weekdayMap;
      }

      // 解析服务时间
      let weekDaysRules = {}
      // console.info("serviceTimes", serviceTimes)
      serviceTimes.forEach(item => {
        let weekdays = item.weekDays.split(",");
        weekdays.forEach(weekday => {
          if (!weekDaysRules[weekday]) {
            weekDaysRules[weekday] = []
          }
          weekDaysRules[weekday].push(item)
        })
      })

      let weekdayMap = {}
      for (let i = 0; i <= 6; i++) {
        if (!weekDaysRules[String(i)]) {
          weekdayMap[String(i)] = [];
          continue;
        }
        let rules = weekDaysRules[String(i)]
        let timeList = []
        for (let j = 0; j < timeSpanList.length; j++) {
          let curTime = timeSpanList[j];
          let flag = false;
          rules.forEach(rule => {
            if (curTime >= rule.beginTime && curTime <= rule.endTime) {
              flag = true;
            }
          })
          if (flag) {
            timeList.push(curTime)
          }
        }
        weekdayMap[String(i)] = timeList;
      }
      return weekdayMap;
    },
    initDisplayInfo(delivery) {
      let { limit, prepareTime, deliveryType } = delivery
      let tabList = [], activeTab = 0, title = "请选择" + TITLE_MAP[deliveryType] + "时间";
      if (limit === 1 && deliveryType === "EXPRESS") {
        // 有预约时间, 并且用户可以不选择备货时间
        tabList = [{ index: 0, title: '标准' },
        { index: 1, title: '预约' + TITLE_MAP[deliveryType] }];
      } else {
        activeTab = 1
      }
      let defaultPrepareTips = "付款后立即" + TITLE_MAP[deliveryType];
      if (prepareTime > 0) {
        if (prepareTime < 60) {
          defaultPrepareTips = "付款后" + prepareTime + "分钟" + TITLE_MAP[deliveryType];
        } else if (prepareTime < 60 * 24) {
          defaultPrepareTips = "付款后" + prepareTime / 60 + "小时后" + TITLE_MAP[deliveryType];
        } else {
          defaultPrepareTips = "付款后" + prepareTime / 60 / 24 + "天后" + TITLE_MAP[deliveryType];
        }
      }
      this.triggerEvent("prepareTips", defaultPrepareTips);
      this.setData({ activeTab, tabList, title, defaultPrepareTips })
    },

    open() {
      this.setData({ dialogShow: true })
    },
    handleSelectTab(e) {
      let index = e.currentTarget.dataset.index;
      this.setData({ activeTab: index })
    },
    handleSelectDay(e) {
      let index = e.currentTarget.dataset.index;
      this.setData({ curIndex: index, curIndex2: null })
    },
    handleSelectTime(e) {
      let index = e.currentTarget.dataset.index;
      this.setData({ curIndex2: index })
    },
    handleContentHeight(e) {
      this.setData({ contentHeight: e.detail })
    },
    handleConfirm(e) {
      if (this.data.tabList.length !== 0 && this.data.activeTab === 0) {
        this.triggerEvent("arrivalTime", "");
        this.setData({ dialogShow: false })
        return;
      }

      if (this.data.curIndex == null || this.data.curIndex2 == null) {
        wx.showToast({
          title: '请选择预约时间',
          icon: 'none',
          duration: 2000
        })
        return;
      }
      if (this.data.curIndex > this.data.dateList.length) {
        wx.showToast({
          title: '请选择预约时间',
          icon: 'none',
          duration: 2000
        })
        this.setData({ curIndex: 0, curIndex2: null })
        return;
      }
      let date = this.data.dateList[this.data.curIndex]
      let minutes = date.timeList[this.data.curIndex2]
      let arrivalTime = dayjs(date.date).add(minutes, 'minutes').format("YYYY-MM-DD HH:mm")
      this.triggerEvent("arrivalTime", arrivalTime);
      this.setData({ dialogShow: false })
    }
  }
})
